<template>
  <!-- 高级检索 -->
  <div class="yu-advanced-search">
    <!-- 模块名称 -->
    <NavigationComponent />
    <!-- 搜索条件 -->
    <div class="searchlist">
      <el-form :inline="true" :model="searchList" class="demo-form-inline">
        <el-form-item label="文件名称">
          <el-input v-model="searchList.fileName" clearable placeholder="请输入文件名称" />
        </el-form-item>

        <el-form-item label="文件类型">
          <el-select @change="onChange" v-model="searchList.fileType" placeholder="请选择文件类型">
            <el-option label="全部" value="" />
            <el-option label="文件" value="file" />
            <el-option label="文件夹" value="folder" />
          </el-select>
        </el-form-item>

        <el-form-item label="文件后缀" v-if="searchList.fileType == 'file'">
          <el-input clearable v-model="searchList.suffix" placeholder="请输入文件后缀" />
        </el-form-item>

        <el-form-item label="编辑时间">
          <el-dropdown ref="updateTimeDropdownRefs">
            <span class="el-dropdown-link">
              {{ updateTimeParams.label }}
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </span>

            <template #dropdown>
              <el-dropdown-menu>
                <div
                  v-for="item in timeList"
                  :key="item.value"
                  class="search_list_item_time"
                  :class="updateTimeParams.value == item.value ? 'timeActive' : ''"
                  @click="updateTimeClick(item)"
                >
                  {{ item.label }}
                </div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-dropdown ref="createTimeDropdownRefs">
            <span class="el-dropdown-link">
              {{ createTimeParams.label }}
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <div
                  v-for="item in timeList"
                  :key="item.value"
                  class="search_list_item_time"
                  :class="createTimeParams.value == item.value ? 'timeActive' : ''"
                  @click="createTimeClick(item)"
                >
                  {{ item.label }}
                </div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>

        <el-form-item label="选择标签" v-if="pageType == 'personal'">
          <el-select
            @remove-tag="removeTag"
            ref="selectref"
            @visible-change="visibleType"
            v-model="dataForm"
            multiple
            placeholder="请选择标签"
            value-key="id"
          >
            <el-option v-for="item in dataForm" :key="item.id" :label="item.labelName" :value="item">
              <span style="float: left">{{ item.labelName }}</span>
              <span>{{ item.code }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格数据 -->
    <div class="table_box">
      <el-table
        v-loading="loading"
        v-if="tableData && tableData.length > 0"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :row-style="{ height: '52px' }"
        :header-row-style="{ height: '52px' }"
        @row-dblclick="handleRowDblClick"
      >
        <el-table-column label="名称" prop="realName" show-overflow-tooltip>
          <template #default="scope">
            <svg-icon :icon-class="selectSvgIcons(scope.row)" style="font-size: 30px; vertical-align: middle; margin-right: 6px"></svg-icon>
            <span class="realName_class">{{ scope.row.realName }}{{ scope.row.suffix ? '.' + scope.row.suffix : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="大小">
          <template #default="scope">
            {{ proxy?.$yuUtils.filterSizeUnit(scope.row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="修改时间"> </el-table-column>
      </el-table>
      <el-empty v-else :image-size="200"></el-empty>
    </div>

    <!-- 分页 -->
    <el-pagination
      v-if="tableData && tableData.length > 0"
      @size-change="getSizeChange"
      @current-change="getPageChange"
      v-model:current-page="commonParams.page"
      :page-sizes="[20, 30, 50, 100]"
      v-model:page-size="commonParams.size"
      layout="total, prev, pager, next, sizes"
      :total="commonParams.total"
    />

    <!-- 个人标签弹窗 -->
    <el-dialog title="标签选择" v-model="isGive" width="30%">
      <div>
        <div class="tagInput">
          <el-input :prefix-icon="Search" clearable placeholder="搜索标签" v-model="query" @keyup.enter.native="UserSelect" />
        </div>
        <el-table
          ref="multiTableRef"
          :data="tagsArray"
          height="400px"
          style="width: 100%"
          @select="selectChange"
          @select-all="selectAllChange"
          @selection-change="selectionChangeHandler"
        >
          <el-table-column type="selection" label="" width="55"></el-table-column>
          <el-table-column prop="labelName" label="名称"></el-table-column>
          <el-table-column prop="createTime" label="创建时间"> </el-table-column>
        </el-table>

        <el-pagination
          @size-change="tagSizeChange"
          @current-change="tagPageChange"
          v-model:current-page="tagsPage.page"
          :page-sizes="[20, 30, 50, 100]"
          v-model:page-size="tagsPage.size"
          layout="total, prev, pager, next, sizes"
          :total="tagsPage.total"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, defineProps, defineEmits, getCurrentInstance } from 'vue';
import moment from 'moment'; // 时间转化
const { proxy } = getCurrentInstance() as any;

import { ArrowDown, Search } from '@element-plus/icons-vue';
import NavigationComponent from './components/navigation-title.vue'; // 导航信息
import { ApiPerFilesInfo, ApiPerfilesUserLabel, ApiPerGetParentTreeNodeAll } from '@/api/personDoc/personDocApi';
const updateTimeDropdownRefs = ref(null);
const createTimeDropdownRefs = ref(null);
const selectref = ref(null);

const multiTableRef = ref(null);
const query = ref('');
const isGive = ref(false);
const loading = ref(false);

const searchList = reactive({
  fileName: '', // 文件名称
  fileType: '', // 文件类型
  suffix: '' // 文件后缀
});

//搜索弹框页码
const tagsPage = reactive({
  // 我的标签分页
  page: 1,
  size: 20,
  total: 0
});

const commonParams = reactive({
  //外层列表
  page: 1,
  size: 20,
  total: 0
});

// 页面表格的数据
const tableData = ref([]);
const selections = ref([]);

// 标签表格的数据
const tagsArray = ref([]);

//选中的数据(我的标签)
const dataForm = ref([]);
const updateTimeParams = reactive({ value: 'any', label: '所有', type: '' });
const createTimeParams = reactive({ value: 'any', label: '所有', type: '' });

//时间列表 type:6.年份 (YEAR)、5.月份 (MONTH)、 4.日期 (DAY)、 3.小时 (HOUR)、 2.分钟 (MINUTE)、1.秒钟 (SECOND)
const timeList = reactive([
  { value: '0', label: '今天', type: '4' },
  { value: '-1', label: '昨天', type: '' }, //如果为-1 传开始时间和结束时间
  { value: '1', label: '一天内', type: '4' },
  { value: '3', label: '3天内', type: '4' },
  { value: '7', label: '7天内', type: '4' },
  { value: '15', label: '15天内', type: '4' },
  { value: '30', label: '30天内', type: '4' },
  { value: 'any', label: '所有' } //什么都不传
]);

const props = defineProps({
  pageType: String
});

/**icon转换 */
const selectSvgIcons = (v: any) => {
  return proxy.$yuUtils.selectSvgIcon(v);
};

/**********************************************搜索start */
// 文件类型选择
const onChange = () => {
  searchList.suffix = '';
};

// 查询
const onSubmit = () => {
  getTableData();
  console.log('submit!');
};

// 获取table列表数据
const getTableData = async () => {
  loading.value = true;
  let labelTypeIds;

  let oParam = {
    page: commonParams.page - 1,
    size: commonParams.size,
    type: 'team',

    ...searchList,
    ...createTime(),
    ...updateTime(),
    labelIds: dataForm.value.map((item) => item.id),
    labelTypeIds: labelTypeIds
  };

  await ApiPerFilesInfo(oParam).then((res) => {
    if (res.code == 200) {
      tableData.value = res.data.rows;
      commonParams.total = res.data.total;
      loading.value = false;
    }
  });
};

// 获取个人标签
const getTags = async () => {
  let oParam = {
    page: tagsPage.page - 1,
    size: tagsPage.size,
    labelName: query.value
  };
  await ApiPerfilesUserLabel(oParam).then((res) => {
    console.log('🚀 ~ getTags ~ res:', res);
    tagsArray.value = res.data.rows;
    tagsPage.total = res.data.total;
  });
};

//编辑时间
const updateTimeClick = (val: any) => {
  console.log('🚀 ~ updateTimeClick ~ val:', val);
  updateTimeParams.label = val.label;
  updateTimeParams.value = val.value;
  updateTimeParams.type = val.type;

  // 调用 hide 方法关闭下拉菜单
  updateTimeDropdownRefs.value?.handleClose();
};

// 创建时间格式化
const createTime = () => {
  let createParams = {};
  if (createTimeParams.value == 'any') {
    createParams = {};
  } else if (createTimeParams.value == '-1') {
    createParams = {
      'createDate.startTime': moment().subtract(1, 'days').format('YYYY-MM-DD'),
      'createDate.endTime': moment().subtract(1, 'days').format('YYYY-MM-DD')
    };
  } else {
    createParams = {
      'createDate.type': createTimeParams.type,
      'createDate.num': createTimeParams.value
    };
  }
  return createParams;
};

//编辑时间
const createTimeClick = (val: any) => {
  createTimeParams.label = val.label;
  createTimeParams.value = val.value;
  createTimeParams.type = val.type;

  // 调用 hide 方法关闭下拉菜单
  createTimeDropdownRefs.value?.handleClose();
};

// 修改时间格式化
const updateTime = () => {
  let updateParams = {};
  // 更新时间传参
  if (updateTimeParams.value == 'any') {
    updateParams = {};
  } else if (updateTimeParams.value == '-1') {
    updateParams = {
      'update.startTime': moment().subtract(1, 'days').format('YYYY-MM-DD'),
      'update.endTime': moment().subtract(1, 'days').format('YYYY-MM-DD')
    };
  } else {
    updateParams = {
      'update.type': updateTimeParams.type,
      'update.num': updateTimeParams.value
    };
  }
  return updateParams;
};

const removeTag = (tag: any) => {
  multiTableRef.value.toggleRowSelection(tag, false);
};

// 是否显示下拉框
const visibleType = (e: any) => {
  //弹框
  isGive.value = true;
  console.log('🚀 ~ visibleType ~ isGive:', isGive.value);
  selectref.value?.blur();
};

/**********************************************搜索end */

/**********************************************首页表格start */
// 双击事件
const handleRowDblClick = async (row) => {
  let params = {
    id: row.id,
    fileType: 0
  };
  const res = await ApiPerGetParentTreeNodeAll(params);
  // console.log('🚀 ~ 双击事件 ~ res:', res);
  let expandedKeys = res.data.map((item) => {
    let obj = {
      id: parseInt(item.id),
      label: item.realName
    };
    return obj;
  });

  sessionStorage.setItem('expandedKeys', JSON.stringify(expandedKeys));

  proxy.$router.push({ path: '/newUi/networkDisk/doc' });
};

// 切换页数
const getSizeChange = (val) => {
  commonParams.size = val;
  getTableData();
};

// 切换条数
const getPageChange = (val) => {
  commonParams.page = val;
  getTableData();
};
/**********************************************首页表格end */

/**********************************************弹框标签start */
// 调用标签接口
const UserSelect = (e) => {
  query.value = e;
  getTags();
};

/**
 * 用于树形表格多选，单选的封装
 * @param selection
 * @param row
 */

const selectChange = (selection, row) => {
  // 如果selection中存在row代表是选中，否则是取消选中
  if (
    selection.find((val) => {
      return getDataId(val) === getDataId(row);
    })
  ) {
    if (row.children) {
      //注意这里的children是后台返回数据的children字段
      row.children.forEach((val) => {
        multiTableRef.value.toggleRowSelection(val, true);
        selection.push(val);
        if (val.children) {
          selectChange(selection, val);
        }
      });
    }
  } else {
    toggleRowSelection(selection, row);
  }
};

/**
 * 切换选中状态
 * @param selection
 * @param data
 */
const toggleRowSelection = (selection, data) => {
  if (data.children) {
    //注意这里的children也是后台返回数据的children字段
    data.children.forEach((val) => {
      multiTableRef.value.toggleRowSelection(val, false);
      if (val.children) {
        toggleRowSelection(selection, val);
      }
    });
  }
};
const getDataId = (data) => {
  return data['id'];
};

/**
 * 用于树形表格多选, 选中所有
 * @param selection
 */

const selectAllChange = (selection) => {
  // 如果选中的数目与请求到的数目相同就选中子节点，否则就清空选中
  if (selection && selection.length === dataForm.value.length) {
    selection.forEach((val) => {
      selectChange(selection, val);
    });
  } else {
    multiTableRef.value.clearSelection();
  }
};
// 选择改变
const selectionChangeHandler = (val) => {
  selections.value = val;
  unique(selections.value, 'id'); //这里有一个问题就是这样点选完之后，数据有重复，所以根据id手动去重，期待优化
};

//数组去重

const unique = (arr, i) => {
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i].id == arr[j].id) {
        arr.splice(j, 1);
        j--;
      }
    }
  }
  dataForm.value = arr;
};

// 切换页数 (标签)
const tagSizeChange = (val) => {
  tagsPage.size = val;
  getTags();
};

// 切换条数 (标签)
const tagPageChange = (val) => {
  tagsPage.page = val;
  getTags();
};

/**********************************************弹框标签end */

onMounted(() => {
  getTableData();
  getTags();

});
</script>

<style lang="scss" scoped>
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.yu-advanced-search {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.table_box {
  height: calc(100vh - 230px);
  overflow: auto;
  margin-left: 20px;
}

.el-form {
  display: flex;
  flex-wrap: wrap;
}
.searchlist {
  margin-top: 20px;
  padding-left: 20px;
  border-bottom: 1px solid #eee;
}
.el-pagination {
  padding: 0px 16px;
  // margin-left: 20px;
}

.search_list_item_time {
  padding: 6px 12px;
  width: 73px;
  font-size: 12px;
  color: #767575;
  cursor: pointer;
  &:hover {
    background-color: #f0f0f0;
  }
}
.timeActive {
  background-color: #f0f0f0;
}

.tagInput {
  // margin: 0 20px;

  :deep(.el-input__wrapper) {
    box-shadow: none !important;
    border: none !important;
    border-bottom: 1px solid #eee !important;
  }
}
</style>
